package com.dwyinyuan.infrastructure.util.utils;

import org.springframework.util.*;

import javax.validation.*;
import java.util.*;


/**
 * 微信公众号：笛舞音缘
 * <p>
 * 校验工具类
 * <p>
 * Created by andy  on 2020-12-16.
 */
public class ValidatorUtils {

    /**
     * 校验器
     */
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 参数校验
     *
     * @param object
     * @param groups
     * @param <T>
     */
    public static <T> void validate(T object, Class... groups) {
        Set<ConstraintViolation<T>> validate = validator.validate(object, groups);

        // 如果校验结果不为空
        if (!CollectionUtils.isEmpty(validate)) {
            StringBuilder exceptionMessage = new StringBuilder();
            validate.forEach(constraintViolation -> {
                exceptionMessage.append(constraintViolation.getMessage());
            });

            throw new RuntimeException(exceptionMessage.toString());
        }
    }

}
